# -*- shell-script -*-

set -eu

GLSLC='@GLSLC@'

message() { echo "glslc: ${@}" >&2; }
message_check() { echo -n "glslc: ${@} ... " >&2; }
message_result() { echo "${@}" >&2; }
error() { echo "glslc:ERROR: ${@}" >&2; }
fatal() { echo "glslc:FATAL: ${@}" >&2; exit 1; }

if [ x"${GLSLC}" = x ]; then
    message "NOTE: glsl validator missing, validation skipped"
fi

FORCE=0
SRCDIR=
SHADERS=
while [ ${#} -gt 0 ]; do
    case "${1}" in
        -f) FORCE=1; shift;;
        -s) SRCDIR="${2}"; shift 2;;
        -*) fatal "invalid option: ${1}";;
        *) SHADERS="${SHADERS} ${1}"; shift;;
    esac
done

test -d "${SRCDIR}" || fatal "invalid srcdir: '${SRCDIR}'"

ERRORS=0
: >glslc.log
for SHADER in ${SHADERS}; do
    SHADER_SOURCE="${SRCDIR}/${SHADER}"
    SHADER_LOG="${SHADER}.log"
    SHADER_AST="${SHADER}.ast"
    STAMP="${SHADER}.stamp-h"
    if test ! -f "${SHADER_SOURCE}"; then
        error "shader not found: '${SHADER_SOURCE}'"
        ERRORS=$((ERRORS + 1))
    elif test ${FORCE} -ne 0 -o ! -f "${STAMP}" -o "${SHADER_SOURCE}" -nt "${STAMP}"; then
        message_check "C ${SHADER}"
        echo "C ${SHADER_SOURCE}" >>glslc.log
        "${GLSLC}" -i "${SHADER_SOURCE}" >"${SHADER_AST}" || true
        if "${GLSLC}" "${SHADER_SOURCE}" >"${SHADER_LOG}" 2>&1; then
            message_result "OK"
            echo >"${STAMP}"
        else
            message_result "ERROR"
            ERRORS=$((ERRORS + 1))
            sed -e "s,^ERROR[[:blank:]]*:[[:blank:][:digit:]]*:,${SHADER_SOURCE}:,g" "${SHADER_LOG}" >>glslc.log
            # cat "${SHADER_LOG}" >>glslc.log
        fi
    else
        message "- ${SHADER_SOURCE}"
    fi
done

if test ${ERRORS} -gt 0; then
    error "${ERRORS} shaders failed:"
    cat glslc.log >&2
    exit 1
fi

message "all done!"
